package com.hp.springboot.dao;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;

/**
 * TODO 注释
 *
 * @author hupan
 * @date 2022-01-02 13:42
 */
public class TxtReplace {

    static final String REGEX_IPV4 = "^\t(\\d{2,})$";
    static final String ENCODE = "UTF-8";
    BufferedReader br = null;
    BufferedWriter bw = null;

    public void copyFile() throws IOException {
        try {
            Pattern pattern = Pattern.compile(REGEX_IPV4);
            br = new BufferedReader(new InputStreamReader(new FileInputStream("C:\\Users\\HuPan\\Desktop\\Elasticsearch实战与原理解析_14729918\\FreePic2Pdf_bkmk.txt"), ENCODE));
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("C:\\Users\\HuPan\\Desktop\\Elasticsearch实战与原理解析_14729918\\FreePic2Pdf_bkmk_2.txt")));
            String line = null;
            while ((line = br.readLine()) != null) {
                StringBuffer sbr = new StringBuffer();
                Matcher matcher = pattern.matcher(line);
                while (matcher.find()) {
                    // 有字符串fatcatfatcatfat,假设既有正则表达式模式为"cat"，第一次匹配后调用appendReplacement(sb,"dog"),那么这时StringBuffer
                    // sb的内容为fatdog，也就是fatcat中的cat被替换为dog并且与匹配子串前的内容加到sb里，而第二次匹配后调用appendReplacement(sb,"dog")，那么sb的内容就变为fatdogfatdog，如果最后再调用一次appendTail（sb）,那么sb最终的内容将是fatdogfatdogfat。
                    String numStr = matcher.group();
                    int num = Integer.parseInt(StringUtils.trim(numStr));
                    matcher.appendReplacement(sbr, (num + 12) + "");
                }
                // 将最后一次匹配工作后剩余的字符串添加到一个StringBuffer对象里
                matcher.appendTail(sbr);
                bw.write(sbr.toString());
                bw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            bw.close();
            br.close();
        }

    }

    public static void main(String[] args) throws IOException {
        new TxtReplace().copyFile();
    }


}
